<template>
  <div>
    <Search v-model="params" placeholder="搜索卡券名称"
      style="z-index: 1000; position: relative;"
      shape="round" autocomplete="off"
      @focus="isFocus = true"
      @blur="isFocus = false"
      @clear="emit('clear')"
      @cancel="emit('clear')" />

    <Popup :z-index="999" v-model:show="isFocus"
      position="top" duration="0.2">
      <Divider
        style="margin-bottom: var(--van-search-input-height);">
      </Divider>
      <CellGroup v-if="!params.length">
        <template #title>
          <div class="history-title">
            <span class="title">历史记录</span>
            <span class="clear-history"
              @click="handleClearHistory">清空历史记录</span>
          </div>
        </template>
        <template v-if="historyList.length">
          <SwipeCell
            v-for="history in historyList"
            :key="history.cardProductId">
            <Cell
              @click="handleSelect(history as any)"
              :title="history.cardProductName" />
            <template #right>
              <Button square type="danger"
                @click="handleDelete(history)"
                text="删除" />
            </template>
          </SwipeCell>
        </template>
        <Empty description="暂无搜索记录" v-else />
      </CellGroup>
      <CellGroup title="搜索结果" v-else>
        <Cell :title="card.cardProductName"
          @click="handleSelect(card)"
          v-for="card in filterCardList"
          :key="card.cardProductId" />
      </CellGroup>
    </Popup>
  </div>
</template>
<script setup lang="ts">
import {
  Button,
  Cell, CellGroup, Divider, Empty, Popup, Search,
  SwipeCell,
} from 'vant';
import {
  computed, onMounted, type PropType, ref,
} from 'vue';
import { useRouter } from 'vue-router';

import type CardItem from '@/views/home-page/models/CardItem';

const params = defineModel('value', {
  type: String,
  default: () => ({ cardProductName: '' }),
});
const emit = defineEmits(['clear']);

const router = useRouter();
const props = defineProps({
  stateCardList: {
    type: Array as PropType<CardItem[]>,
    default: () => [],
  },
  idKey: {
    type: String,
    default: 'historyList',
  },
});
const historyList = ref<{ cardProductName: string; cardProductId: string }[]>([]);

onMounted(() => {
  const histories = localStorage.getItem(props.idKey);
  if (histories && histories.length) {
    historyList.value = JSON.parse(histories);
  } else {
    historyList.value = [];
  }
});

const filterCardList = computed(() => props.stateCardList
  .filter((item) => item.cardProductName.includes(params.value)));
const isFocus = ref(false);

const handleSelect = (card: CardItem) => {
  const index = historyList.value.findIndex((item) => item.cardProductId === `${card.cardProductId}`);
  if (index > -1) {
    historyList.value.splice(index, 1);
  }
  historyList.value.push({
    cardProductName: card.cardProductName,
    cardProductId: `${card.cardProductId}`,
  });
  localStorage.setItem(props.idKey, JSON.stringify(historyList.value));
  router.push({ name: 'CardSubmit', params: { id: `${card.cardProductId}` } });
};

const handleDelete = (history: { cardProductName: string; cardProductId: string }) => {
  const index = historyList.value.findIndex((item) => item.cardProductId === history.cardProductId);
  if (index > -1) {
    historyList.value.splice(index, 1);
  }
  localStorage.setItem(props.idKey, JSON.stringify(historyList.value));
};

const handleClearHistory = () => {
  historyList.value = [];
  localStorage.setItem(props.idKey, JSON.stringify(historyList.value));
};
</script>
<style lang="less" scoped>
.history-title {
  font-size: 14px;
  padding: 10px 0;
  display: flex;

  .clear-history {
    margin-left: auto;
  }
}
</style>
